from flask import Flask, request, jsonify, send_from_directory
import mysql.connector
from werkzeug.security import generate_password_hash

app = Flask(__name__, static_folder='static', template_folder='templates')

@app.route('/')
def index():
    return send_from_directory(app.static_folder, 'zhuce.html')

# 配置MySQL连接
config = {
    'user': 'myuser',
    'password': '123456',
    'host': '127.0.0.1',
    'port': '3306',
    'database': 'dbsclab2018'
}

@app.route('/user/register', methods=['POST'])
def register():
    # 获取前端发送的数据
    username = request.json.get('uname')
    password = request.json.get('password')

    if not username or not password:
        return jsonify({'code': '1', 'msg': '用户名和密码不能为空'}), 400

    # 加密密码
    hashed_password = generate_password_hash(password)

    # 创建数据库连接
    db_connection = mysql.connector.connect(**config)
    cursor = db_connection.cursor()

    # 插入用户名和哈希密码到数据库
    try:
        cursor.execute("INSERT INTO users (username, password) VALUES (%s, %s)", (username, hashed_password))
        db_connection.commit()
        return jsonify({'code': '0', 'msg': '用户注册成功'}), 201
    except mysql.connector.Error as err:
        return jsonify({'code': '2', 'msg': '用户名已存在'}), 400
    finally:
        cursor.close()
        db_connection.close()

if __name__ == '__main__':
    app.run(debug=True, port=3000)



